﻿using System;
using System.Threading;
using System.Web;
using Hourglass.Qrobot.Http;
using Hourglass.Qrobot.Utils;

namespace Hourglass.Qrobot.States
{
    public class WattingForScanQRCodeState : QQState
    {
        private readonly Random _random;

        public WattingForScanQRCodeState()
        {
            this._random = new Random();
        }

        public override void Handler(QQContext context)
        {
            while (true)
            {
                var para = context.ToLoginScanStatusRequest();
                var response = DataProvider.GetLoginScanStatus(para);
                var splits = response.Split('\'');
                switch (splits[1])
                {
                    case "66":
                        Thread.Sleep(context.Config.LoginQRValidateInternal);
                        continue;
                    case "67":
                        context.Displayer.DisplayStatus("扫码完成，正在认证");
                        Thread.Sleep(context.Config.LoginQRValidateInternal);
                        continue;
                    case "65":
                        context.Displayer.DisplayStatus("二维码已失效，将重新获取二维码");
                        context.State = new WattingForGetQRCodeState();
                        return;
                    case "0":
                        DataProvider.LoginSigCheck(context.ToLoginSigCheckRequest(splits[5]));
                        context.VerfiedField.Vfwebqq = DataProvider.GetLoginVfwebqq(context.ToLoginVfwebqqRequest(TimeHelper.MilliscondFromSeventy()));
                        var psandqq = DataProvider.GetLoginPsessionidWithQq(context.ToLoginPsessionRequest());
                        context.VerfiedField.Psessionid = psandqq.Psessionid;
                        context.VerfiedField.Qq = psandqq.Qq;
                        context.VerfiedField.Qhash = HashHelper.QqHash(context.VerfiedField.Qq, context.VerfiedField.Ptwebqq);
                        context.Displayer.DisplayStatus("登录成功");
                        context.State = new LoginedWarmUpState(); 
                        return;
                    default:
                        context.Displayer.DisplayStatus($"获取到位置响应码{splits[1]}，完整响应[{response}]");
                        throw new ArgumentException($"unknow QRCode state{splits[1]}", response);
                }
            }
        }
    }
}
